<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isNew ? '添加期限' : '编辑期限'"
    top="35vh"
    width="450px"
    :before-close="close"
    :close-on-click-modal="false"
    append-to-body
  >
    <el-scrollbar max-height="60vh" v-loading="loading">
      <el-form
        ref="formRef"
        :model="formData"
        label-width="80px"
        :rules="rules"
      >
        <el-form-item label="时间期限" prop="deadlineDate">
          <el-date-picker
            v-model="formData.deadlineDate"
            type="date"
            format="YYYY年MM月DD日"
            value-format="YYYY-MM-DD 23:59:59"
            :disabled-date="disabledDate"
          />
        </el-form-item>
        <el-form-item label="关键期限" prop="isKey">
          <KeySelect v-model="formData.isKey" />
        </el-form-item>
        <el-form-item label="期限要求" prop="deadlineRequire">
          <el-input
            v-model="formData.deadlineRequire"
            type="textarea"
            :rows="6"
            :maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
    </el-scrollbar>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="submit()" :loading="loading">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { reactive, ref, useTemplateRef } from 'vue'
import { FormInstance, FormRules } from 'element-plus'
import { disabledDate } from '@/plugins/date'
import KeySelect from '@/components/statusShow/key/KeySelect.vue'

const emit = defineEmits(['update', 'add'])
const formRef = useTemplateRef<FormInstance>('formRef')

const dialogVisible = ref(false)
const loading = ref(false)
const isNew = ref(true)
const rowIndex = ref(null)

const formData = reactive({
  deadlineDate: null,
  isKey: 0,
  deadlineRequire: null,
})

const rules = ref<FormRules<typeof formData>>({
  deadlineDate: {
    required: true,
    message: '请选择时间期限',
    trigger: 'change',
  },
})

defineExpose({ show })

function show(row?: any, index?: number) {
  dialogVisible.value = true
  if (row) {
    isNew.value = false
    formData.deadlineDate = row.deadlineDate
    formData.isKey = row.isKey
    formData.deadlineRequire = row.deadlineRequire
    rowIndex.value = index
  }
}

function close() {
  dialogVisible.value = false
  loading.value = false
  isNew.value = true
  rowIndex.value = null
  Object.assign(formData, {
    deadlineDate: null,
    isKey: 0,
    deadlineRequire: null,
  })
}

function submit() {
  formRef.value.validate((bool) => {
    if (!bool) {
      return
    }

    if (rowIndex.value !== null) {
      emit('update', formData, rowIndex.value)
    } else {
      emit('add', [formData])
    }
    close()
  })
}
</script>

<style scoped lang="scss">
:deep(.el-date-editor) {
  width: 100%;
}
</style>
